<template>
  <div v-if="visiable1">
    <div style="display: flex">
      <div v-for="(item,index) in $store.state.videoListUpload" :key="index" v-if="showFlag">
        <div style="display: flex;flex-direction: column" v-if="!isBlank(item.videoCover)">
          <img :src="imageUtils(imgUrl,item.videoCover)" @click="handleView(item)" style="width: 60px;height: 60px;margin-right: 10px" alt="">
          <div>
            <el-upload class="upload-demo" accept=".jpg,.jpeg,.png,.webp" action="" :before-upload="handleChangeCover">
              <el-button size="mini" round @click="handleCover(item,index)">更换封面</el-button>
            </el-upload>
          </div>
        </div>
      </div>
    </div>
    <el-upload class="upload-demo" action="#" :on-change="beforeUpload" :auto-upload="false" :show-file-list="false" multiple accept=".mp4">
      <el-button size="small" type="primary">添加文件</el-button>
      <el-tooltip content="仅支持上传MP4文件,图裂开不代表视频上传失败" placement="top">
        <i class="el-icon-question" style="color: red"/>
      </el-tooltip>
    </el-upload>
    <div style="width: 65%;">
      <div v-for="(item,index) in $store.state.videoListUpload" :key="index">
        <div style="display: flex;flex-direction: column">
          <div style="display: flex;">
            <div style="color: red;margin-right: 5px;cursor: pointer" @click="hanleDeleteItem(item,index)">
              <i class="el-icon-delete-solid"/>
            </div>
            <div>{{ item.name }}</div>
            <div v-if="isFlag(item.percentage,100)" style="color: green"><i class="el-icon-success"/></div>
          </div>
          <div v-if="isFlag(item.videoUploadFlag,true)">
            <el-progress :percentage="item.percentage" :color="colors"></el-progress>
          </div>
        </div>
      </div>
    </div>
    <el-button @click="handleUpload" v-if="$store.state.videoListUpload.length>0">点击上传</el-button>
  </div>
</template>

<script>
import store from "@/store/index";
import appUtils, { isBlank, initCacheData, isFlag, ossPut, videoListOssUpload } from "@/utils/util";
import { imageUtils } from "@/utils/imageUtil";

export default {
  props: ["imgUrl", "maxNumber", 'fileSize'],
  name: "videoListUpload",
  data() {
    return {
      showFlag: true,
      visiable1: true,
      uploadFlag: false,
      itemIndex: null,
      colors: [
        { color: '#909399', percentage: 25 },
        { color: '#e6a23c', percentage: 50 },
        { color: '#409eff', percentage: 75 },
        { color: '#67c23a', percentage: 100 }
      ]
    }
  },
  watch: {},
  methods: {
    isFlag,
    imageUtils,
    isBlank,
    beforeUpload(file) {
      let fileSize = 10
      let maxNumber = 3
      if (!isBlank(this.fileSize)) {
        fileSize = this.fileSize
      }
      if (!isBlank(this.maxNumber)) {
        maxNumber = this.maxNumber
      }
      console.log(store.state.videoListUpload.length)
      this.handleMaxSize(file, fileSize).then(res => {
        if (isFlag(res, true)) {
          if (store.state.videoListUpload.length < maxNumber) {
            store.state.videoListUpload.push(file)
          } else {
            store.state.videoListUpload.splice(maxNumber - 1, 1, file)
          }
        }
      })
    },
    //限定文件最大
    handleMaxSize(file, size) {
      const fileSize = file.size / 1024 / 1024 < size
      return new Promise((resolve, reject) => {
        if (!fileSize) {
          this.$notify.error({
            title: '文件过大',
            message: '请不要超过' + size + 'MB.'
          })
          return resolve(false)
        } else {
          return resolve(true)
        }
      })
    },
    handleCover(param, index) {
      this.itemIndex = index
    },
    handleChangeCover(file) {
      console.log(file)
      const fileRaw = file
      let cover = ''
      if (!isBlank(fileRaw)) {

        cover = ossPut(fileRaw, this.imgUrl)
      }
      setTimeout(() => {
        console.log(cover)
        this.$set(store.state.videoListUpload[this.itemIndex], 'videoCover', cover)
        this.showFlag = false
        this.showFlag = true
      }, 500)
    },
    hanleDeleteItem(param, index) {
      store.state.videoListUpload.splice(index, 1)
      console.log(store.state.videoListUpload)
    },
    handleUpload() {
      store.state.videoListUpload.forEach((file, index) => {
        if (!isFlag(file.percentage, 100) || isBlank(file.percentage)) {
          new Promise((resolve) => {
            videoListOssUpload(this.imgUrl, file, index)
            setTimeout(() => {
              resolve(true)
            }, 1000)
          }).then((res) => {
            console.log(res)
            setTimeout(() => {
              this.findVideoPoster(file).then(res => {
                file.videoCover = res
                this.showFlag = false
                this.showFlag = true
              })
            }, 500)
          })
        }
      })
    },
    updateDom() {
      this.visiable1 = false;
      this.showFlag = false
      this.$nextTick(() => {
        this.visiable1 = true;
        this.showFlag = true
      });
    },
    handleView(param) {
      window.open(appUtils.myImage + this.imgUrl + param.fileName)
    },
    findVideoPoster(param) {
      let file = param.raw
      let self = this
      return new Promise(function(resolve) {
        let base64URL = ''
        let video = document.createElement('video')
        video.setAttribute('crossOrigin', 'anonymous') //处理跨域
        video.setAttribute('src', URL.createObjectURL(file))
        video.currentTime = 1
        video.addEventListener('loadeddata', function() {
          let canvas = document.createElement('canvas')
          //使用视频的宽高作为canvas、预览图的宽高
          let width = video.videoWidth
          let height = video.videoHeight
          canvas.width = width
          canvas.height = height
          canvas.getContext('2d').drawImage(video, 0, 0, width, height) //绘制canvas
          base64URL = canvas.toDataURL('image/jpeg') //转换为base64，图片格式默认为png，这里修改为jpeg
          let fileName = String(new Date().getTime()) + parseInt(Math.random() * 100000) + '.jpeg'
          let fileNew = self.convertFile(base64URL, fileName)
          let fileName1 = ossPut(fileNew, self.imgUrl)
          resolve(fileName1)
        })
      })
    },
    convertFile(base64, fileName) {
      console.log(fileName)
      let fileArray = base64.split(','),
        fileType = fileArray[0].match(/:(.*?);/)[1],
        bstr = atob(fileArray[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], fileName, { type: fileType })
    }
  }
}
</script>

<style scoped>

</style>
